package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.AdminFeign;
import com.bwie.auth.service.AdminService;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Admin;
import com.bwie.common.domain.request.AdminRequest;
import com.bwie.common.domain.response.AdminResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author：作者姓名
 * @Package：com.bwie.auth.service.impl
 * @Project：_yk
 * @name：AdminServiceimpl
 * @Date：2024/5/17 9:26
 */
@Service
public class AdminServiceimpl implements AdminService {

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;




    @Override
    public Result<AdminResponse> login(AdminRequest adminRequest) {
        Result<Admin> adminResult = adminFeign.FindBy(adminRequest.getUserName());
        Admin admin = adminResult.getData();
        if(admin==null){
            throw new RuntimeException("用户名不存在");
        }
        if(StringUtils.isAllBlank(adminRequest.getUserName(),adminRequest.getPwd())){
            throw new RuntimeException("用户名或密码不能为空");
        }
        if(!adminRequest.getPwd().equals(admin.getPwd())){
            throw new RuntimeException("密码不正确");
        }

        String uuid = UUID.randomUUID().toString();
        HashMap<String, Object> map = new HashMap<>();
        map.put(TokenConstants.LOGIN_TOKEN_KEY,uuid);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+"uuid",
                JSONObject.toJSONString(admin),
                TokenConstants.EXPIRATION, TimeUnit.MINUTES);
        AdminResponse adminResponse = new AdminResponse();
        adminResponse.setMinTime("720MIN");
        adminResponse.setToken(token);

        return Result.success(adminResponse);
    }
}
